<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图区域 -->
        <el-card class="box-card">
            <!-- 搜索视图区域 -->
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-input placeholder="请输入内容" v-model="queryUserInfo.query" clearable>
                        <el-button slot="append" icon="el-icon-search" @click="getUserList()"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="6">
                    <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>
            <!-- 用户数据展示区域 -->
            <el-table :data="userlist" border stripe>
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column prop="username" label="姓名"></el-table-column>
                <el-table-column prop="email" label="邮箱"></el-table-column>
                <el-table-column prop="mobile" label="电话"></el-table-column>
                <el-table-column prop="role_name" label="角色"></el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <!-- 修改按钮 -->
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditUser(scope.row.id)">
                        </el-button>
                        <!-- 删除按钮 -->
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)">
                        </el-button>
                        <!-- 分配角色按钮 -->
                        <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                            <el-button type="warning" icon="el-icon-setting" size="mini"
                                @click="showSetRoleDialog(scope.row)">
                            </el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页区域 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="queryUserInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryUserInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </el-card>
        <!-- 添加用户的对话框 -->
        <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
            <!-- 内容主体区域 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="addForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <!-- 内容下边条区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改用户对话框 -->
        <el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
                <el-form-item label="用户名">
                    <el-input v-model="editForm.username" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="邮箱地址" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="电话号码" prop="mobile">
                    <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUserInfo()">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 分配角色对话框 -->
        <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%" @close="setRoleDialogClosed">
            <p>当前的用户：{{userInfo.username}}</p>
            <p>当前的角色：{{userInfo.role_name}}</p>
            <p>
                分配新角色：<el-select v-model="selectedRoleId" placeholder="请选择">
                    <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
                    </el-option>
                </el-select>
            </p>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveSetUserRole">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        data() {
            // 自定义邮箱验证规则
            var checkEmail = (rule, value, callback) => {
                const regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
                if (regEmail.test(value)) {
                    return callback()
                }
                return callback(new Error('请输入合法的邮箱'))
            }
            // 自定义手机验证规则
            var checkMobile = (rule, value, callback) => {
                const regMobile = /^1[34578]\d{9}$/
                if (regMobile.test(value)) {
                    return callback()
                }
                return callback(new Error('请输入合法的手机号'))
            }
            return {
                queryUserInfo: {
                    query: '',
                    // 当前页数
                    pagenum: 1,
                    // 当前每页显示多少条数据
                    pagesize: 2
                },
                total: 0,
                userlist: [],
                // 控制添加用户对话框的显示与隐藏
                addDialogVisible: false,
                editDialogVisible: false,
                // 查询的用户数据
                editForm: {
                },
                editFormRules: {
                    email: [
                        { required: false, message: '请输入邮箱', trigger: 'blur' },
                        { validator: checkEmail, trigger: 'blur' }
                    ],
                    mobile: [
                        { required: false, message: '请输入手机号', trigger: 'blur' },
                        { validator: checkMobile, trigger: 'blur' }
                    ]
                },
                // 添加的用户数据
                addForm: {
                    username: '',
                    password: '',
                    email: '',
                    mobile: ''
                },
                addFormRules: {
                    username: [
                        { required: true, message: '请输入用户名', trigger: 'blur' },
                        { min: 3, max: 10, message: '长度在 3 到 10 个字符之间', trigger: 'blur' }
                    ],
                    password: [
                        { required: true, message: '请输入密码', trigger: 'blur' },
                        { min: 6, max: 15, message: '长度在 6 到 15个字符之间', trigger: 'blur' }
                    ],
                    email: [
                        { required: false, message: '请输入邮箱', trigger: 'blur' },
                        { validator: checkEmail, trigger: 'blur' }
                    ],
                    mobile: [
                        { required: false, message: '请输入手机号', trigger: 'blur' },
                        { validator: checkMobile, trigger: 'blur' }
                    ]
                },
                setRoleDialogVisible: false,
                userInfo: {},
                rolesList: [],
                // 已选中的role的id值
                selectedRoleId: ''
            }
        },
        created() {
            this.getUserList()
        },
        methods: {
            async getUserList() {
                const { data: res } = await this.$http.get('users', { params: this.queryUserInfo })
                if (res.meta.status !== 200) { return this.$message.error(res.meta.msg) }
                this.pagenum = res.data.pagenum
                this.total = res.data.total
                this.userlist = res.data.users
            },
            // 监听当前每页显示多少条数据
            handleSizeChange(newSize) {
                this.queryUserInfo.pagesize = newSize
                this.getUserList()
            },
            // 监听当前是第几页
            handleCurrentChange(newPage) {
                this.queryUserInfo.pagenum = newPage
                this.getUserList()
            },
            // 监听用户状态的改变
            async userStateChange(stateInfo) {
                const { data: res } = await this.$http.put(`users/${stateInfo.id}/state/${stateInfo.mg_state}`)
                if (res.meta.status !== 200) {
                    stateInfo.mg_state = !stateInfo.mg_state
                    return this.$message.error(res.meta.msg)
                }
                this.$message.success(res.meta.msg)
            },
            //监听弹框关闭事件
            addDialogClosed() {
                this.$refs.addFormRef.resetFields()
            },
            //添加用户
            addUser() {
                this.$refs.addFormRef.validate(async valid => {
                    if (!valid) return
                    //可以发起添加用户的网络请求
                    const { data: res } = await this.$http.post('users', this.addForm)
                    console.log(res)
                    if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
                    this.$message.success('添加用户成功')
                    this.addDialogVisible = false
                    this.getUserList()
                })
            },
            //编辑用户信息
            async showEditUser(id) {
                const { data: res } = await this.$http.get('users/' + id)
                console.log(res);
                if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
                this.editForm = res.data;
                this.editDialogVisible = true
            },
            //监听关闭重置事件
            editDialogClosed() {
                this.$refs.editFormRef.resetFields()
            },
            //添加表单编辑预验证
            editUserInfo() {
                this.$refs.editFormRef.validate(async valid => {
                    if (!valid) return
                    //发起修改用户的请求
                    const { data: res } = await this.$http.put('users/' + this.editForm.id, {
                        email: this.editForm.email,
                        mobile: this.editForm.mobile
                    })
                    if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
                    this.$message.success('修改用户信息成功')
                    this.editDialogVisible = false
                    this.getUserList()
                })
            },
            //删除用户
            async deleteUser(id) {
                const res = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(error => {
                    return error
                })
                //如果确认删除用户，则返回值为字符串confirm
                //如果取消了删除，则返回值为字符串cancel
                if (res !== 'confirm') {
                    return this.$message.info('已取消删除')
                }
                const { data: ret } = await this.$http.delete('users/' + id)
                console.log(ret);
                if (ret.meta.status !== 200) { return this.$message.error(ret.meta.msg) }
                this.getUserList()
                this.$message.success('删除用户成功')
            },
            //分配用户角色
            async showSetRoleDialog(userInfo) {
                this.userInfo = userInfo
                const { data: res } = await this.$http.get('roles')
                if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
                this.rolesList = res.data
                console.log(this.userInfo);
                this.setRoleDialogVisible = true

            },
            // 点击按钮，分配角色
            async saveSetUserRole() {
                if (!this.selectedRoleId) {
                    this.$message.error('请选择用户要分配的角色')
                }
                const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectedRoleId })
                if (res.meta.status !== 200) {
                    return this.$message.error('设置角色失败')
                }
                this.$message.success('设置角色成功')
                this.getUserList()
                this.setRoleDialogVisible = false
            },
            setRoleDialogClosed() {
                this.selectedRoleId = ''
                this.userInfo = ''
            }
        }

    }
</script>

<style lang="less" scoped>
    .el-card {
        box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;
    }
</style>